const axios = require('axios');
const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

const apiUrl = 'http://localhost:11434/api/chat'; 

 chart=()=> {
    rl.question('请输入你的问题（输入 "退出" 结束程序）: ', (question) => {
        if (question === '退出') {
            rl.close();
            return;
        }
      
        const requestData = {
            model: 'deepseek-r1:1.5b', 
            messages: [
                {
                    role: 'user',
                    content: question
                }
            ]
        };
      
        axios.post(apiUrl, requestData, { responseType: 'stream' })
           .then(response => {
                let fullResponse = '';
                response.data.on('data', (chunk) => {
                    const lines = chunk.toString().split('\n');
                    for (const line of lines) {
                        if (line.trim() === '') continue;
                        try {
                            const jsonObj = JSON.parse(line);
                            if (jsonObj.message && jsonObj.message.content) {
                                fullResponse += jsonObj.message.content;
                            }
                        } catch (parseError) {
                            console.error('解析响应数据出错: ', parseError.message);
                        }
                    }
                });

                response.data.on('end', () => {
                    console.log('回复: ', fullResponse);                   
                    chart();
                });
            })
           .catch(error => {
                console.error('请求出错: ', error.message);               
                chart();
            });
    });
}

chart();

// 当 readline 接口关闭时，结束程序
rl.on('close', () => {
    console.log('程序已结束');
});
